package software;

/**
 * Author by KyrieC
 * Created by sheting on 2023/12/7
 */
public class Stopwatch {
    private long startTime;
    private long elapsedTime;
    private boolean isRunning;

    // 构造方法
    public Stopwatch() {
        startTime = 0;
        elapsedTime = 0;
        isRunning = false;
    }

    // 开始计时
    public void start() {
        if (!isRunning) {
            startTime = System.currentTimeMillis();
            isRunning = true;
        }
    }

    // 暂停计时
    public void pause() {
        if (isRunning) {
            elapsedTime += System.currentTimeMillis() - startTime;
            isRunning = false;
        }
    }

    // 继续计时
    public void resume() {
        if (!isRunning) {
            startTime = System.currentTimeMillis();
            isRunning = true;
        }
    }

    // 停止计时
    public void stop() {
        if (isRunning) {
            elapsedTime += System.currentTimeMillis() - startTime;
            isRunning = false;
            startTime = 0;
        }
    }

    // 获取计时结果，单位为毫秒
    public long getElapsedTime() {
        if (isRunning) {
            return elapsedTime + System.currentTimeMillis() - startTime;
        } else {
            return elapsedTime;
        }
    }

    public String parseTotime(Long elapsedTime){
        if (elapsedTime < 1000) {
            return "0" + "秒";
        }
        long second = elapsedTime / 1000;
        long seconds = second % 60;
        long minutes = second / 60;
        long hours = 0;
        if (minutes >= 60) {
            hours = minutes / 60;
            minutes = minutes % 60;
        }
        String timeString = "";
        String secondString = "";
        String minuteString = "";
        String hourString = "";
        if (seconds < 10) {
            secondString = "0" + seconds + "秒";
        } else {
            secondString = seconds + "秒";
        }
        if (minutes < 10 && hours < 1) {
            minuteString = minutes + "分";
        } else if (minutes < 10){
            minuteString =  "0" + minutes + "分";
        } else {
            minuteString = minutes + "分";
        }
        if (hours < 10) {
            hourString = hours + "时";
        } else {
            hourString = hours + "" + "时";
        }
        if (hours != 0) {
            timeString = hourString + minuteString + secondString;
        } else {
            timeString = minuteString + secondString;
        }
        return timeString;
    }
}